#!/usr/bin/env python
import os
import sys
from subprocess import Popen, PIPE
import usrfix

def done(code = 0):
    print '\n</body>\n</html>' 
    sys.exit(code)

# Print the content header
print 'Content-type: text/html'
print """
<html>
<head>
    <title>Update Server</title>
    <style type="text/css">
        * {
            margin:  0;
            padding: 0;
        }

        body {
            font-family: 'Droid Sans', 'Helvetica', 'Arial', sans;
            padding: 1em;
        }

        pre {
            font-family: 'Droid Sans Mono', monospaced;
        }

        h2 {
            margin-bottom: 0.7em;
        }

        div {
            width: 600px;
            max-height: 300px;
            overflow: auto;
            padding: 1em;
            margin-bottom: 1em;
        }
        
        .info {
            border: 2px solid #000;
            color: #fff;
            background: #000;
        }

        .error {
            border: 2px solid #f00;
            color: #f00;
            background: #ffc4c4;
        }
    </style>
</head>
<body>
"""

# Update the files from subversion
print '\t<h2>Updating SVN definitions<br/></h2>'
proc = Popen('svn up', shell = True, stdout = PIPE, stderr = PIPE)
resp = proc.communicate()

if len(resp[0]) != 0:
    print '\t<div class="info">\n<pre>%s</pre>\n\t</div>' % resp[0].strip()
    if len(resp[1]) != 0: print '\t<br/>'
if len(resp[1]) != 0:
    print '\t<div class="error">\n<pre>%s</pre>\n\t</div>'  % resp[1].strip()
    done(1)
print ''

# Fix any invalid permissions
print '\t<h2>Updating permissions</h2>'
print '\t<div class="info">\n<pre>\n%s</pre>\n\t</div>\n' % usrfix.fix_perms()

# Restart the server
print '\t<h2>Restarting Site Server</h2>'
print '\t<div class="info">\n<pre>\ntouch django.fcgi</pre>\n\t</div>\n'
os.system('touch django.fcgi')
done()
